Right Shift Operator (>>) with Signed Integers
When using the bitwise right shift (>>
) operator with signed integers, it’s essential to understand how the sign bit is preserved and the implications of this preservation. Let’s explore this with examples:
Preserving Sign Bit:
In signed integers, the leftmost bit (most significant bit) represents the sign of the number. When right-shifting signed integers, the sign bit is preserved, meaning it is replicated to fill the vacant leftmost positions.
Example:
# Signed right shift
x = -8 # Binary: 1111 1000 (assuming 8-bit signed integer)
y = x >> 1 # Binary: 1111 1100, Decimal: -4
In this example, when -8
is right-shifted by 1 position, the sign bit (1
) is replicated, resulting in 1111 1100
, which represents -4
in decimal.
Use Case: Division by Powers of 2 with Signed Integers
#include <iostream>
int main() {
int num = -16;
int divisor = 4;
int result = num >> 2; // Equivalent to num / 2^2
std::cout << result << std::endl; // Output: -4
return 0;
}
public class Main {
public static void main(String[] args) {
int num = -16;
int divisor = 4;
int result = num >> 2; // Equivalent to num / 2^2
System.out.println(result); // Output: -4
}
}
# Division by powers of 2 using right shift with signed integers
num = -16
divisor = 4
result = num >> 2 # Equivalent to num // 2**2
print(result) # Output: -4
using System;
class Program
{
static void Main(string[] args)
{
int num = -16;
int result = num >> 2; // Equivalent to num / 2^2
Console.WriteLine(result); // Output: -4
}
}
//This code is contributed by Adarsh.
// JavaScript pprogram
// Main function
function main() {
let num = -16;
let result = num >> 2; // Equivalent to num / 2^2
console.log(result);
}
// Call the main function to execute the program
main();
Output
-4
In this case, -16
is right-shifted by 2 positions, which is equivalent to dividing -16
by 2**2
. The sign bit is preserved during the right shift, resulting in -4
.
Right Shift Operator (>>) in Programming
Right shift operator (>>), commonly found in programming languages, including C, C++, Java, and others, is used to shift the bits of a number to the right by a specified number of positions. Each shift moves all bits in the operand to the right by the number of positions indicated by the right operand.
Table of Content
- Right Shift Operator (>>) Definition
- Right Shift Operator (>>) Syntax
- Right Shift Operator (>>) Examples
- Right Shift Operator (>>) with Signed Integers
- Right Shift Operator (>>) with Unsigned Integers
- Right Shift Operator (>>) with Signed vs. Unsigned Integers
- Logical Right Shift
- Arithmetic Right Shift
- Logical Right Shift vs. Arithmetic Right Shift
- Right Shift Operator (>>) Optimization Techniques
- Bit Manipulation Hacks with Right Shift Operator
This comprehensive guide aims to provide a deep understanding of bitwise right shift operators, from the foundational principles to advanced optimization strategies.
Contact Us